<template>
  <div>
    <Timeline>
      <TimelineItem v-for="(item, index) in list" :key="index" style="min-height: 50px">
        <template #dot>
          <div
            style="width: 10px; height: 10px; background-color: #cccccc; border-radius: 50%"
          ></div>
        </template>
        <div
          class="flex justify-between pb-15px gap-2"
          style="border-bottom: 1px solid #f6f6f6; font-size: 16px"
        >
          <div>
            <div>{{ item.title }}</div>
            <div style="color: #8d8e8c; font-size: 14px">{{ item.subTitle }}</div>
          </div>
          <div class="flex items-center gap-2 flex-1">
            <div class="flex items-center gap-2 flex-1 flex-wrap justify-end">
              <div v-for="(el, ind) in item.usersSelected" :key="ind">
                <template v-if="item.ActionApplicantSelScope == '1'">
                  <Checkbox
                    v-if="item.ActionApplicantSelMode == '1'"
                    v-model:checked="el['checked']"
                    @change="(e) => handleChangeUsersSelected(e, el, ind, item)"
                    >{{ el.realName }}</Checkbox
                  >
                  <Radio
                    v-if="item.ActionApplicantSelMode == '0'"
                    v-model:checked="el['checked']"
                    @change="(e) => handleChangeUsersSelected(e, el, ind, item)"
                    >{{ el.realName }}</Radio
                  >
                </template>
                <Button
                  v-if="item.ActionApplicantSelScope == '0' || item.ActionApplicantSelScope == '2'"
                >
                  {{ el.realName }}
                  <CloseOutlined @click.stop="handleDeleteUser(el, item)" />
                </Button>
              </div>
            </div>
            <div style="width: 30px">
              <Badge
                :dot="item.usersSelected.length ? false : true"
                :offset="[-6, 2]"
                v-if="item.ActionApplicantSelScope == '0' || item.ActionApplicantSelScope == '2'"
              >
                <plus-circle-outlined
                  style="font-size: 30px; cursor: pointer; color: #bcb8b9"
                  @click="handleSelectUserAdd(item, index)"
                />
              </Badge>
            </div>
          </div>
        </div>
      </TimelineItem>
    </Timeline>
    <SelectUser @register="registerSelectUserModal" @success="handleSuccessSelectUserModal" />
  </div>
</template>
<script lang="ts" setup>
  import { ref, watch } from 'vue';
  import { useModal } from '/@/components/Modal';
  import { SelectUser } from '/@/components/CustomComp/index';
  import { PlusCircleOutlined, CloseOutlined } from '@ant-design/icons-vue';

  import { cloneDeep } from 'lodash-es';
  import { setActionUser } from '/@/api/process/process';
  import { Timeline, Badge, Checkbox, Button, Radio } from 'ant-design-vue';
  const TimelineItem = Timeline.Item;
  const props = defineProps({
    matchBranchAndUserActions: {
      type: Array,
      default: () => [],
    },
  });
  const emit = defineEmits(['success']);
  const list = ref<any>([]);
  const currentIndex = ref(-1);

  watch(
    () => props.matchBranchAndUserActions,
    (newVal: any) => {
      if (newVal && newVal.length) {
        list.value = cloneDeep(newVal).map((item) => {
          if (item.ActionApplicantSelScope == '1') {
            //人员
            if (item.usersSelected.length == 0) {
              item.usersSelected = item.ActionApplicantAssignedUsers.map((el) => {
                return {
                  ...el,
                  checked: false,
                };
              });
            } else {
              const usersSelected = item.usersSelected.map((el) => el.userName);
              item.usersSelected = item.ActionApplicantAssignedUsers.map((el) => {
                return {
                  ...el,
                  checked: usersSelected.includes(el.userName),
                };
              });
            }
          }
          return {
            ...item,
          };
        });
      } else {
        list.value = [];
      }
    },
    {
      immediate: true,
    },
  );

  const [registerSelectUserModal, { openModal: openModalSelectUser }] = useModal();
  //选人
  const handleSelectUserAdd = (item, index) => {
    currentIndex.value = index;
    openModalSelectUser(true, {
      users: item.usersSelected.map((el) => {
        return {
          name: el.userName,
          realName: el.realName,
        };
      }),
      tabKeys: item.ActionApplicantSelScope == '2' ? ['3'] : [],
      showRoleKeys:
        item.ActionApplicantSelScope == '2'
          ? item.ActionApplicantAssignedRoles.map((el) => el.code)
          : [],
      type: item.ActionApplicantSelMode == '0' ? 0 : 1,
    });
  };
  //选人回调
  const handleSuccessSelectUserModal = (data) => {
    if (data && data.length > 0) {
      if (list.value[currentIndex.value]) {
        const keys = list.value[currentIndex.value].usersSelected.map((el) => el.userName);
        data.forEach((item) => {
          if (list.value[currentIndex.value].ActionApplicantSelMode == 0) {
            list.value[currentIndex.value].usersSelected = [
              {
                userName: item.key,
                realName: item.title,
              },
            ];
          } else {
            if (!keys.includes(item.key)) {
              list.value[currentIndex.value].usersSelected.push({
                userName: item.key,
                realName: item.title,
              });
            }
          }
        });
      }
    } else {
      list.value[currentIndex.value].usersSelected = [];
    }
    list.value = [...list.value];
    handleSave(list.value[currentIndex.value]);
  };

  //保存
  const handleSave = async (item) => {
    const data =
      item.ActionApplicantSelScope == '1'
        ? item.usersSelected.filter((el) => el.checked)
        : item.usersSelected;
    try {
      let params = {
        id: item.id,
        users: data.map((el) => {
          return {
            userName: el.userName,
            realName: el.realName,
          };
        }),
      };
      await setActionUser(params);
      emit('success');
    } catch (error) {
      console.error(error);
    }
  };

  //已选
  const handleChangeUsersSelected = (e, el, ind, item) => {
    if (item.ActionApplicantSelMode == '0') {
      item.usersSelected.forEach((ti, iti) => {
        if (iti == ind) {
          ti.checked = true;
        } else {
          ti.checked = false;
        }
      });
    }
    handleSave(item);
  };
  //删除已选
  const handleDeleteUser = (el, item) => {
    item['usersSelected'] = item['usersSelected'].filter((fi) => fi != el);
    handleSave(item);
  };

  const checkActionUserSelected = () => {
    let isSelected = true;
    console.log('checkActionUserSelected', list.value);
    list.value.forEach((item) => {
      if (item.ActionApplicantSelScope == '1') {
        let ary = item.usersSelected.filter((el) => el.checked);
        if (ary.length == 0) {
          isSelected = false;
          return;
        }
      } else {
        if (!item.usersSelected || item.usersSelected.length == 0) {
          isSelected = false;
          return;
        }
      }
    });
    return isSelected;
  };

  defineExpose({
    checkActionUserSelected,
  });
</script>
